import sqlite3, datetime
from django.shortcuts import render
from django.http import HttpResponse
from shared_resources import *
	
def feedback(request, student_id):
	student_id = to_int(student_id)
	initialize(request)
	output = ""
	
	has_rights = request.session["rights"]["edit_students"] or (request.session["user"]["type"] == 1 and request.session["user"]["id"] == student_id)
	if not has_rights:
		output += '<p class="error_message">'+t('You do not have the rights to view feedback for this student.')+'</p>'
	else:
		sql_connection = sqlite3.connect(global_vars["database"])
		sql_cursor = sql_connection.cursor()    
		class_feedback = {}
		db_rows = sql_cursor.execute("""select comment, time, lesson_id, (select class_id from lessons where lessons.id = lesson_id), on_time, did_homework from student_feedback where student_id = ? order by time desc""", (student_id, ))
		for comment, timestamp, lesson_id, class_id, on_time, did_homework in db_rows:
			class_feedback[class_id] = class_feedback.get('class_id', {})
			class_feedback[class_id][lesson_id] = {"comment": comment, "timestamp": timestamp, "lesson_id": lesson_id, "class_id": class_id, "on_time": on_time, "did_homework": did_homework}
		
		if len(class_feedback) == 0:
			output += t("No feedback yet.")
		
		for student_class in class_feedback:
			result = sql_cursor.execute("""select (select first_name from staff where staff.id = teacher_id), (select middle_name from staff where staff.id = teacher_id), (select last_name from staff where staff.id = teacher_id), subject from classes where id = ?""", (student_class, )).fetchone()
			first_name, middle_name, last_name, subject = result
			output += "<h3>" + display_name(first_name, middle_name, last_name) + " - "+ class_subjects[subject] +"</h3>"
			for lesson_id in class_feedback[student_class]:
				values = class_feedback[student_class][lesson_id]
				output += '<div class="alert alert-warning alert-dismissible"><b>'+stamp_to_display(values["timestamp"], "date_time_format")+'</b><br />'+values["comment"] + '<br /><br />'+t('Did homework: <b>%s</b>, One time: <b>%s</b>', ((t("yes", (), True) if on_time == 1 else t("no", (), True)), (t("Yes", (), True) if did_homework == 1 else t("no", (), True))))+'</b></div>'
		
	return format_response(t("Teacher feedback"), output)

